package com.powernode.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BusinessEnum;
import com.powernode.model.Result;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description:
 * @author: mky
 * @date: 2024/7/5 11:35
 * @version: 1.0
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType(AuthConstants.CONTENT_TYPE);
        response.setCharacterEncoding(AuthConstants.UTF_8);
        Result<Object> result = new Result<>();
        result.setCode(BusinessEnum.LOGINFAILURE.getCode());
        if (exception instanceof BadCredentialsException) {
            result.setMsg("用户名或密码有误");
        } else if (exception instanceof UsernameNotFoundException) {
            result.setMsg("用户名不存在");
        } else if (exception instanceof AccountExpiredException) {
            result.setMsg("帐号异常，请联系管理员");
        } else if (exception instanceof InternalAuthenticationServiceException) {
            result.setMsg(exception.getMessage());
        } else {
            result.setMsg(BusinessEnum.LOGINFAILURE.getMsg());
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(result);
        PrintWriter writer = response.getWriter();
        writer.write(s);
        writer.flush();
        writer.close();
    }
}
